package cn.micai.base.concurrent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Vector;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/7/6 10:54
 * @Description: 使用客户端加锁，对Vector进行复合操作
 */
public abstract class AbstractVector {

    public static Object getLast(Vector list) {
        synchronized (list) {
            int lastIndex = list.size() - 1;
            return list.get(lastIndex);
        }
    }

    public static void deleteLast(Vector list) {
        synchronized (list) {
            int lastIndex = list.size() -1;
            list.remove(lastIndex);
        }
    }

    /**
     * 使用客户端加锁进行迭代，避免产生ArrayIndexOutOfBoundsException异常
     * @param list
     */
    public static void foreachLast(Vector list) {
        synchronized (list) {
            for (int i=0; i<list.size(); i++) {
                doSomething(list.get(i));
            }
        }
    }

    public static void foreachList(List<Widget> widgetList) {
        if (widgetList == null) {
            widgetList = Collections.synchronizedList(new ArrayList<Widget>());
        }
        // 1.多线程的情况下，会出现并发修改容器的可能，可能抛出ConcurrentModificationException
        // 2.ConcurrentModificationException也可能出现在单线程的代码中；当对象并非通过Iteraror.remove，而是直接从容器中删除时，
        // 就会出现这个异常
        for (Widget widget : widgetList) {
            doSomething(widget);
        }
    }

    private static void doSomething(Object o) {
        System.out.println(o);
    }

}
